package com.rules.core.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Spring Context 工具类
 */
@Component
public class SpringContextUtils implements ApplicationContextAware {

	public static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		SpringContextUtils.applicationContext = applicationContext;
	}

	public static Object getBean(String name) {
		return applicationContext.getBean(name);
	}

	/**
	 * 根据beanName获取bean
	 *
	 * @param name beanName
	 * @return bean的实例
	 * @throws BeansException BeansException
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBeanByName(String name) throws BeansException {
		return applicationContext == null ? null : (T) applicationContext.getBean(name);
	}

	/**
	 * 根据beanName获取bean
	 *
	 * @param T 获取bean的类型
	 * @return bean的实例
	 * @throws BeansException BeansException
	 */
	public static <T> T getBeanByClass(Class<T> T) throws BeansException {
		return applicationContext == null ? null : applicationContext.getBean(T);
	}

	/**
	 * <p>
	 * 方法说明: 根据接口获取所有的实现类bean
	 *
	 * @param clazz 接口类
	 * @return 接口实现类bean集合
	 */
	public static <T> Map<String, T> getBeansOfType(Class<T> clazz) {
		@SuppressWarnings("rawtypes")
		Map<String, T> beanMaps = applicationContext.getBeansOfType(clazz);
		if (beanMaps != null && !beanMaps.isEmpty()) {
			return beanMaps;
		} else {
			return null;
		}
	}

	public static <T> T getBean(String name, Class<T> requiredType) {
		return applicationContext.getBean(name, requiredType);
	}

	public static boolean containsBean(String name) {
		return applicationContext.containsBean(name);
	}

	public static boolean isSingleton(String name) {
		return applicationContext.isSingleton(name);
	}

	public static Class<? extends Object> getType(String name) {
		return applicationContext.getType(name);
	}

}
